#!/bin/sh
# PCP QA Test No. 1763
# pmlogctl - LOCALHOSTNAME vs hostname confusion
#
# Copyright (c) 2020 Ken McDonell.  All Rights Reserved.
#

if [ $# -eq 0 ]
then
    seq=`basename $0`
    echo "QA output created by $seq"
else
    # use $seq from caller, unless not set
    [ -n "$seq" ] || seq=`basename $0`
    echo "QA output created by `basename $0` $*"
fi

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

_cleanup()
{
    cd $here
    pmlogctl status -c $seq >$tmp.tmp 2>&1
    $PCP_AWK_PROG <$tmp.tmp '$3 == '$seq' { print "bozo" }' >$tmp.test
    if [ -s $tmp.test ]
    then
	echo "Unexpected pmloggers in -c $seq ..."
	cat $tmp.tmp
	$sudo pmlogctl destroy -f -c $seq
    fi
    $sudo rm -rf $tmp $tmp.*
}

status=0	# success is the default!
$sudo rm -rf $tmp $tmp.* $seq.full
trap "_cleanup; exit \$status" 0 1 2 3 15

# Note status command output order is non-deterministic, hence the sort
# at the end
#
_filter_status()
{
    tee -a $seq.full \
    | $PCP_AWK_PROG -f $tmp.awk \
    | sed >$tmp.tmp \
	-e "/^`hostname` .* primary /d" \
	-e 's/[ 	][ 	]*/ /g' \
	-e 's/2[0-9][0-9][0-9][01][0-9][0-3][0-9]\...\.[^ ]*/<archivename>/' \
	-e "s/^`hostname` /HOSTNAME /" \
	-e "s/ $seq / <seq> /" \
	-e 's/ [0-9][0-9]* / <pid> /' \
    # end
    head -1 $tmp.tmp
    sed -e '1d' $tmp.tmp | LC_COLLATE=POSIX sort
}

# Build filter for any existing non-qa and non-primary pmlogger instances.
# The "pmcd Host" and "Class" fields from the pmlogctl status output
# should suffice to uniquely identify each.
#
pmlogctl status 2>&1 \
| $PCP_AWK_PROG >$tmp.awk '
NR == 1	{ next }
NF >= 5	{ if ($3 == "primary") next
	  print "$1 == \"" $1 "\" && $3 == \"" $3 "\" { next }"
	}
END	{ print "{ print }" }'

# trivial pmlogger config
#
echo "log mandatory on 10sec { sample.lights }" >$tmp.config

# real QA test starts here

# LOCALHOSTNAME
#
echo "=== LOCALHOSTNAME ==="
cat >$tmp.ctl <<End-of-File
# Installed by PCP QA test $seq on `date`
\$version=1.1
\$class=$seq
LOCALHOSTNAME  n n PCP_ARCHIVE_DIR/$seq -c $tmp.config
End-of-File
$sudo cp $tmp.ctl $PCP_ETC_DIR/pcp/pmlogger/control.d/$seq
$sudo $PCP_BINADM_DIR/pmlogger_check

echo "Expect installed and running ..."
pmlogctl -V status | _filter_status
$sudo pmlogctl -f -c $seq destroy
echo "Expect no longer present ..."
pmlogctl -V status | _filter_status

# hostname(1)
#
echo
echo "=== hostname(1) ==="
cat >$tmp.ctl <<End-of-File
# Installed by PCP QA test $seq on `date`
\$version=1.1
\$class=$seq
`hostname`  n n PCP_ARCHIVE_DIR/$seq -c $tmp.config
End-of-File
$sudo cp $tmp.ctl $PCP_ETC_DIR/pcp/pmlogger/control.d/$seq
$sudo $PCP_BINADM_DIR/pmlogger_check

echo "Expect installed and running ..."
pmlogctl -V status | _filter_status
$sudo pmlogctl -f -c $seq destroy
echo "Expect no longer present ..."
pmlogctl -V status | _filter_status

# success, all done
exit
